# coding: utf-8
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

"""
CryptoClient module.

Created on 12/29/2017

@author: 强哥
"""

ADD_STR = '\0'
 
class CryptoClient():
	"""

	字符串加密解密
	必须是相同的key加密过的字符串, 才能解密
	"""
	def __init__(self, key='keyskeyskeyskyes'):
		self.__mode = AES.MODE_CBC
		self.__key = key

	def __getCryptoInstance(self):
		"""

		AES 加密实例
		"""
		return AES.new(self.__key, self.__mode, self.__key)

	def __makeLength16Text(self, text):
		"""
		
		要加密的字符串长度, 使用占位字符串, 增加到16的倍数
		"""
		return "".join([text, ADD_STR * (16 - (len(text) % 16))])

	def __stripLength16Text(self, text):
		"""

		解密后的字符串去除加密前增加的占位字符串
		"""
		return text.rstrip(ADD_STR)

	def enCrypt(self, text):
		"""

		加密字符串
		"""
		cryptor = self.__getCryptoInstance()
		return b2a_hex(cryptor.encrypt(self.__makeLength16Text(text)))
	 
	def deCrypt(self, text):
		"""

		解密字符串
		"""
		cryptor = self.__getCryptoInstance()
		return self.__stripLength16Text(cryptor.decrypt(a2b_hex(text)))

def example():
	"""

	例子
	decodeStr = 0dac70ade006bc5f2d960beb6efcbecf
	key = keyszslskeyskyes
	"""
	C = CryptoClient()
	# print C.enCrypt('aaa')
	print C.deCrypt('39633f18b0407e6b396b361debf09de0')

if __name__ == '__main__':
	example()